# -*- coding: utf-8 -*-
import py2neo,networkx,gensim,pandas
try:
    graph = py2neo.Graph(password="admin")
except:
    print 'neo4j error'

def welcome():
    # query = '''
    # MATCH (c1:Character)-[r:INTERACTS]->(c2:Character)
    # RETURN c1.name, c2.name, r.weight AS weight LIMIT 25
    # '''
    igstats=graph.data('call apoc.meta.stats')
    igdata=graph.data('call apoc.meta.data')
    iggraph = graph.data('call apoc.meta.graph')
    return dict(message='',ig=igstats,igdata=igdata,iggraph=iggraph)

def calendar():
    return dict(message='')

def login():
    # response.flash = T("Welcome to RS")
    if request.vars.username and request.vars.password:
        db.auth_user.password.requires = CRYPT(key=auth.settings.hmac_key, min_length=0)
        if auth.login_bare(username=request.vars.username,password=request.vars.password):
            session.authorized = True
            session.last_time = t0
            redirect(URL('admin', 'index',args=request.args))
        else:
            response.flash = T('User name or password error！')
    elif request.vars:
        response.flash = T('User name or password is empty！')
    session.counter = (session.counter or 0) + 1
    return dict(message="login", counter=session.counter)

def logout():
    auth.logout_bare()
    redirect(URL('admin','login'))

#@cache(request.env.path_info, time_expire=auth.settings.expiration, cache_model=cache.ram)
def index():
    #response.flash = T("Welcome to PyCube")
    menu = cache.ram(str(session.auth.user.id)+"aaa", lambda: getMenuRoot(), time_expire=1)
    return dict(message='index logo',auth=session.auth,menu=menu)

def getMenuRoot():
    if(session.auth.user.username=='admin'):
        menuRows = db(db.sys_menu.is_show == True).select(orderby=db.sys_menu.sortno)  # 全部权限  后续根据管理员权限判断,暂时直接admin判断
    else:
        menuRows= db( (db.sys_role_menu.group_id.belongs(session.auth.user_groups.keys())) & (db.sys_menu.is_show ==True) ).select(
                   db.sys_menu.ALL,distinct=True,orderby=db.sys_menu.sortno,
                   left=db.sys_role_menu.on(db.sys_role_menu.menu_id == db.sys_menu.id))

    menu=UL(LI(T('Main Nav'),SPAN(_class='sidebar-nav-heading-info'),_class='sidebar-nav-heading'),_class='sidebar-nav')
    #db((db.sys_menu.parent_id == None) & (db.sys_menu.is_show ==True)).select(orderby=db.sys_menu.sortno)
    for parent in menuRows.find(lambda row: row.parent_id == None):
        menu.append(getMenuContent(getMenuChild(parent,menuRows),parent))
    # print menu
    return menu



def getMenuChild(parent,rows):
    ul=UL(_class='sidebar-nav sidebar-nav-sub')
    #db((db.sys_menu.parent_id == parent.id) & (db.sys_menu.is_show ==True )).select(orderby=db.sys_menu.sortno)
    for child in  rows.find(lambda row: row.parent_id == str(parent.id)):
        ul.append(getMenuContent(getMenuChild(child,rows),child))
    return ul

def getMenuContent(content,child):
    list=['am-badge-primary', 'am-badge-secondary', 'am-badge-success', 'am-badge-warning', 'am-badge-danger']
    from random import choice
    return LI(A(SPAN(_class='sidebar-nav-link-logo ' + (child.icon == '' and 'am-icon-clone' or child.icon)),
              child.name,
              content.__len__() != 0 and SPAN(_class='am-icon-chevron-down am-fr am-margin-right-sm sidebar-nav-sub-ico')+SPAN(content.__len__(),_class='am-badge '+choice(list)+' sidebar-nav-link-logo-ico am-round am-fr am-margin-right-sm') or '',
              _href=(child.href == '' and 'javascript:void(0);' or '/' + request.application + child.href),_class =(content.__len__() != 0 and 'sidebar-nav-sub-title' or '') ,
               **{child.href == '' and ' ' or '_target':child.target }
               ), content.__len__() != 0 and content or '',_class='sidebar-nav-link')

def change_password():
    form = auth.change_password(next=URL('pages', 'index'))
    return dict(form=form)

def menu():
    return dict(form=LOAD( 'admin' , 'menuc.load'))

def menuc():
    grid = SQLFORM.grid(db.sys_menu,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def user():
    return dict(form=LOAD('admin', 'userc.load'))

def userc():
    grid = SQLFORM.grid(db.auth_user,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def role():
    return dict(form=LOAD('admin', 'rolec.load'))

def rolec():
    grid = SQLFORM.grid(db.auth_group,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def membership():
    return dict(form=LOAD('admin', 'membershipc.load'))

def membershipc():
    grid = SQLFORM.grid(db.auth_membership,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def rolemenu():
    return dict(form=LOAD('admin', 'rolemenuc.load'))

def rolemenuc():
    grid = SQLFORM.grid(db.sys_role_menu,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def sysdict():
    return dict(form=LOAD('admin', 'sysdictc.load'))

def sysdictc():
    grid = SQLFORM.grid(db.sys_dict,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

#---------------------system end-----------------


def appSlide():
    return dict(form=LOAD('admin', 'appSlidec.load'))

def appSlidec():
    grid = SQLFORM.grid(db.app_slide,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def appInfo():
    return dict(form=LOAD('admin', 'appInfoc.load'))

def appInfoc():
    grid = SQLFORM.grid(db.app_info,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def appType():
    return dict(form=LOAD('admin', 'appTypec.load'))

def appTypec():
    grid = SQLFORM.grid(db.app_type,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def appPhotogroup():
    return dict(form=LOAD('admin', 'appPhotogroupc.load'))

def appPhotogroupc():
    grid = SQLFORM.grid(db.app_photogroup,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def appPhoto():
    return dict(form=LOAD('admin', 'appPhotoc.load'))

def appPhotoc():
    grid = SQLFORM.grid(db.app_photo,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)

def appArtical():
    return dict(form=LOAD('admin', 'appArticalc.load'))

def appArticalc():
    grid = SQLFORM.grid(db.app_artical,paginate=10,searchable=False,csv=False)
    return dict(grid=grid)


def metagraph():
    iggraph = graph.data('call apoc.meta.graph')
    return dict(message='',iggraph=iggraph)

def queryNode():
    listclass=['am-badge-primary', 'am-badge-secondary', 'am-badge-success', 'am-badge-warning', 'am-badge-danger']
    from random import choice
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    labpro=[]
    for rows in igdata:
        if "node"==rows[igdata.keys().index('elementType')] and "RELATIONSHIP"!=rows[igdata.keys().index('type')]:
            labels.append(rows[igdata.keys().index('label')])
            pros.append(rows[igdata.keys().index('property')])
            lp={"l":rows[igdata.keys().index('label')],"p":rows[igdata.keys().index('property')]}
            if lp not in labpro:
                labpro.append(lp)
    labels = list(set(labels))
    pros = list(set(pros))
    labelsA=DIV()
    for label in labels:
        labelsA.append(A(label,_class='am-badge '+choice(listclass)+'  am-round ',_onclick='test(this)'))
    prosA=DIV(_id="lpid")
    for lp in labpro:
        prosA.append(SPAN(lp['p'],_name=lp['l'],_class='am-badge '+choice(listclass)+'  am-round '))
    return dict(message='',labels=labels,pros=pros,labelsA=labelsA,prosA=prosA)
def queryNodeResult():
    node=request.vars.node
    property=request.vars.property
    num=request.vars.num
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match(n:'+node +'{'+property+'}) return n  LIMIT '+num)
    return dict(data=result,time=str(datetime.datetime.now()-begin))

def queryTable():
    igdata=graph.data('call apoc.meta.data')
    return dict(message='',igdata=igdata)

def queryRel():
    listclass=['am-badge-primary', 'am-badge-secondary', 'am-badge-success', 'am-badge-warning', 'am-badge-danger']
    from random import choice
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros = []
    labpro = []
    rels=DIV()
    for rows in igdata:
        if 'RELATIONSHIP'==rows[igdata.keys().index('type')]:
            labels.append(rows[igdata.keys().index('label')])
        if 'RELATIONSHIP'!=rows[igdata.keys().index('type')] and 'relationship'==rows[igdata.keys().index('elementType')]:
            pros.append(rows[igdata.keys().index('property')])
            lp = {"l": rows[igdata.keys().index('label')], "p": rows[igdata.keys().index('property')]}
            if lp not in labpro:
                labpro.append(lp)
    rels.append(A("*", _class='am-badge ' + choice(listclass) + '  am-round ',_onclick='test(this)'))
    labels=list(set(labels))
    for label in labels:
            rels.append(A(label,_class='am-badge '+choice(listclass)+'  am-round ',_onclick='test(this)'))
    relskeys = DIV(_id="lpid")
    for lp in labpro:
        relskeys.append(SPAN(lp['p'], _name=lp['l'], _class='am-badge ' + choice(listclass) + '  am-round '))
    return dict(message='',labels=labels,rels=rels,pros=list(set(pros)),relskeys=relskeys)

def queryRelResult():
    node=request.vars.node
    relkeys = request.vars.relkeys
    num = request.vars.num
    r='[r:'+node+'{'+relkeys+'}]'
    if '*'==node:
       r=''
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=()-'+r+'->() return p  LIMIT '+num)
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                node_obj['category'] ="n"+str(node_obj['id'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def queryNumber():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)

def queryNumberResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')-['+linknode+levkey+']->('+endnode+') return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                node_obj['category'] ="n"+str(node_obj['id'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))



def queryNumberResult_back():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
    endnode=''
    if nodesOption[1]['name']:
        endnode='n:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')-['+linknode+levkey+']->('+endnode+') return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        nodestart={}
        for key in row[0].start_node.keys():
            nodestart[key] =row[0].start_node[key]
        nodestart['id'] = row[0].start_node.identity
        nodestart['draggable'] ='true'
        nodestart['category'] ="n"+str(nodestart['id'])
        if nodestart not in nodes:
            nodes.append(nodestart)
            categorys.append({'name':nodestart['category']})
        nodeend = {}
        for key in row[0].end_node.keys():
            nodeend[key] = row[0].end_node[key]
        nodeend['id'] = row[0].end_node.identity
        nodeend['draggable'] = 'true'
        nodeend['category'] = "n" + str(nodeend['id'])
        if nodeend not in nodes:
            nodes.append(nodeend)
            categorys.append({'name': nodeend['category']})
        noderel={}
        for relkey in row[0].relationships[0].keys():
            noderel[relkey] = row[0].relationships[0][relkey]
        noderel['category'] = ''
        for caa in row[0].types():
            noderel['category'] = caa

        noderel['source'] = nodes.index(nodestart)
        noderel['target'] = nodes.index(nodeend)
        link.append(noderel)
    print nodes,categorys
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def queryShortestPath():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)

def queryShortestPathResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    whereStr=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
        else:
            whereStr=' WHERE id(n) > id(m)'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='..'+nodesOption[2]['name']
    selectpath='shortestPath'
    if nodesOption[2]['prokey']:
        selectpath=nodesOption[2]['prokey']
    import datetime
    begin = datetime.datetime.now()

    result= graph.data('Match ('+startnode+'),('+endnode+') '+whereStr+'  Match p='+selectpath+'((n)-['+linknode+'*'+levkey+']-(m)) return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                node_obj['category'] ="n"+str(node_obj['id'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def queryBetweenness():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)

def queryBetweennessResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
    linknode=''
    link=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        link="'"+linksOption[0]['name']+"'"
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    import datetime

    begin = datetime.datetime.now() #OUTGOING BOTH
    res=graph.data('Match ('+startnode+') WITH collect(n) AS ns CALL apoc.algo.betweenness(['+link+'], ns, \'BOTH\') YIELD node, score  SET node.betweenness = score  RETURN max(score),min(score)')
    result = graph.data('MATCH p=('+startnode+')<-['+linknode+levkey+']->()  return p LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']

                if node_obj.has_key('betweenness') and node_obj['betweenness']>1:
                    node_obj['symbolSize'] =((node_obj['betweenness']-res[0][1])/(res[0][0]-res[0][1]))*100
                    node_obj['category'] = "n"
                else:
                    node_obj['category'] = "m"
                    # float
                    node_obj['symbolSize'] = 50
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                #+str(node_obj['id'])

                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=[{'name':"n","itemStyle": {"normal": {"color": "#0e90d2"}}},{'name':"m","itemStyle": {"normal": {"color": "#8fa8ad"} }}],time=str(end-begin))

def algoLpa():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)


def algoLpaResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    start='null'
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        start="['"+nodesOption[0]['name']+"']"
    linknode=''
    link='null'
    if linksOption[0]['name']:
        linknode = 'r:' + linksOption[0]['name']
        link="'"+linksOption[0]['name']+"'"
    import datetime
    begin = datetime.datetime.now() #OUTGOING BOTH
    graph.run("CALL apoc.algo.community(25,"+start+",'corporation',"+link+",'BOTH','weight',10000)")
    result = graph.data('MATCH p=('+startnode+')-['+linknode+']->() return p LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    categoryslist=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']

                if node_obj.has_key('corporation'):
                    # node_obj['symbolSize'] =((node_obj['betweenness']-res[0][1])/(res[0][0]-res[0][1]))*500
                    node_obj['category'] = "n"+str(node_obj['corporation'])
                else:
                    node_obj['category'] = "m"
                    # float
                    # node_obj['symbolSize'] = 50
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                #+str(node_obj['id'])

                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
                    linkss={'name':str(node_obj['category'])}
                    if linkss not in categoryslist:
                        categoryslist.append(linkss)
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categoryslist,time=str(end-begin))

def queryCommunity():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)


def queryCommunityResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    start='null'
    wherenode=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        # start="['"+nodesOption[0]['name']+"']"
        if nodesOption[0]['prokey']:

            if nodesOption[0]['prokey'].find('in')!=-1:
                wherenode='where n.'+nodesOption[0]['prokey']
            else:
                startnode = startnode + '{' + nodesOption[0]['prokey'] + '}'
    linknode=''
    link='null'
    if linksOption[0]['name']:
        linknode = 'r:' + linksOption[0]['name']
        link="'"+linksOption[0]['name']+"'"
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']


    import datetime
    begin = datetime.datetime.now() #OUTGOING BOTH
    # graph.run("CALL apoc.algo.community(25,"+start+",'corporation',"+link+",'BOTH','weight',10000)")

    if wherenode=='':
        result = graph.data('MATCH p=('+startnode+')<-[' + linknode + levkey + ']->() return p LIMIT ' + nodesOption[4]['name'])
    else:
        result = graph.data('MATCH ('+startnode+') '+wherenode + ' with distinct n as q  MATCH p=(m:'+nodesOption[0]['name']+'{corporation:q.corporation})<-['+linknode+levkey+']->() return p LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    categoryslist=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']

                if node_obj.has_key('corporation'):
                    # node_obj['symbolSize'] =((node_obj['betweenness']-res[0][1])/(res[0][0]-res[0][1]))*500
                    node_obj['category'] = "n"+str(node_obj['corporation'])
                else:
                    node_obj['category'] = "m"
                    # float
                    # node_obj['symbolSize'] = 50
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                #+str(node_obj['id'])

                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
                    linkss={'name':str(node_obj['category'])}
                    if linkss not in categoryslist:
                        categoryslist.append(linkss)
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categoryslist,time=str(end-begin))




def algoGraphLpa():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)

def algoGraphLpaResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    whereStr=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
        else:
            whereStr=' WHERE id(n) > id(m)'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    selectAlgo='0'
    if nodesOption[2]['prokey']:
        selectAlgo=nodesOption[2]['prokey']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')<-['+linknode+levkey+']->('+endnode+') return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()

    nodes=[]
    link=[]
    categorys=[]

    edges = []
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})

                if noderel not in link:
                   link.append(noderel)
                   edges.append((rel.start_node.identity, rel.end_node.identity))
    import networkx as nx
    from networkx.algorithms import community
    G = nx.Graph()
    G.add_edges_from(edges)


    if selectAlgo=="0":
        klist = list(community.label_propagation_communities(G))
    else:
        klist= list(community.kernighan_lin_bisection(G))
    print klist

    categorys = []
    for index, setrow in enumerate(klist):
        print index
        for rowa in setrow:
            for nn in nodes:
                if nn['id']==rowa:
                    nn['category']=index
                    aa = {'name': index}
                    if aa not in categorys:
                        categorys.append(aa)
                    break
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def algoGraphLpaResult__igraph():#__igraph
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    whereStr=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
        else:
            whereStr=' WHERE id(n) > id(m)'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    selectAlgo='0'
    if nodesOption[2]['prokey']:
        selectAlgo=nodesOption[2]['prokey']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')<-['+linknode+levkey+']->('+endnode+') return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()

    nodes=[]
    link=[]
    categorys=[]

    edges = []
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})

                if noderel not in link:
                   link.append(noderel)
                   edges.append((rel.start_node.identity, rel.end_node.identity))

    from igraph import Graph as IGraph
    ig = IGraph.TupleList(edges, weights=True)
    if selectAlgo=="0":
        cc = ig.community_label_propagation()
    else:
        cc=ig.community_multilevel()
    print cc
    membershiplist = cc.membership

    categorys = []
    for index, nn in  enumerate(nodes):
        nn['category']=membershiplist[index]
        aa={'name':membershiplist[index]}
        if aa not in categorys:
            categorys.append(aa)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def algoGraphLpaResult_1():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    whereStr=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
        else:
            whereStr=' WHERE id(n) > id(m)'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    selectAlgo='0'
    if nodesOption[2]['prokey']:
        selectAlgo=nodesOption[2]['prokey']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')-['+linknode+levkey+']->('+endnode+') return n,m,p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    from igraph import Graph as IGraph
    ig = IGraph.TupleList(result, weights=True)
    if selectAlgo=="0":
        cc = ig.community_label_propagation()
    else:
        cc=ig.community_multilevel()
    # print cc
    nodes=[]
    link=[]
    categorys=[]
    membershiplist=cc.membership
    for row in result:
        for path in row[2]:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':"n"+str(node_obj['id'])})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel[relkey] = rel[relkey]
                if noderel.has_key('id'):
                    noderel['_id']=noderel['id']
                noderel['id'] = rel.identity
                noderel['category'] = path_name
                noderel['source'] = categorys.index({'name':"n"+str(rel.start_node.identity)})
                noderel['target'] = categorys.index({'name':"n"+str(rel.end_node.identity)})
                if noderel not in link:
                   link.append(noderel)
    categorys = []
    for index, nn in  enumerate(nodes):
        nn['category']=membershiplist[index]
        aa={'name':membershiplist[index]}
        if aa not in categorys:
            categorys.append(aa)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def algoGraphLpaResult_back():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    whereStr=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
        else:
            whereStr=' WHERE id(n) > id(m)'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    selectpath='shortestPath'
    if nodesOption[2]['prokey']:
        selectpath=nodesOption[2]['prokey']
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+startnode+')-['+linknode+levkey+']->('+endnode+') return n,m  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    from igraph import Graph as IGraph
    ig = IGraph.TupleList(result, weights=True)
    cc = ig.community_label_propagation()
    # cc=ig.community_multilevel()
    print cc
    nodes=[]
    link=[]
    categorys=[]
    membershiplist=cc.membership
    for row in result:
            for node in row[0],row[1]:
                node_obj = {}
                for key in node.keys():
                    node_obj[key]=node[key]
                if node_obj.has_key('id'):
                    node_obj['_id']=node_obj['id']
                node_obj['id'] = node.identity
                node_obj['draggable'] ='true'
                # node_obj['category'] ="n"+str(node_obj['id'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name': "n" + str(node_obj['id'])})
            noderel = {}
            noderel['source'] = categorys.index({'name':"n"+str(row[0].identity)})
            noderel['target'] = categorys.index({'name':"n"+str(row[1].identity)})
            noderel['category'] = ''
            if noderel not in link:
               link.append(noderel)
    categorys = []
    for index, nn in  enumerate(nodes):
        nn['category']=membershiplist[index]
        aa={'name':membershiplist[index]}
        if aa not in categorys:
            categorys.append(aa)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))

def graphCrud():
    igdata = graph.data('call apoc.meta.data')
    labels=[]
    pros=[]
    for rows in igdata:
        labels.append(rows[igdata.keys().index('label')])
        pros.append(rows[igdata.keys().index('property')])
    labels = list(set(labels))
    pros = list(set(pros))
    return dict(message='',labels=labels,pros=pros)

def graphCrudResult():
    nodesOption = request.vars.series[0]['data']
    linksOption = request.vars.series[0]['links']
    startnode=''
    if nodesOption[0]['name']:
        startnode='n:'+nodesOption[0]['name']
        if nodesOption[0]['prokey']:
            startnode=startnode+'{'+nodesOption[0]['prokey']+'}'
    endnode=''
    if nodesOption[1]['name']:
        endnode='m:'+nodesOption[1]['name']
        if nodesOption[1]['prokey']:
            endnode=endnode+'{'+nodesOption[1]['prokey']+'}'
    linknode=''
    if linksOption[0]['name']:
        linknode='r:'+linksOption[0]['name']
        if linksOption[0]['prokey']:
            linknode=linknode+'{'+linksOption[0]['prokey']+'}'
    levkey=''
    if nodesOption[2]['name']:
        levkey='*..'+nodesOption[2]['name']
    import datetime
    begin = datetime.datetime.now()
    if levkey=='' and linknode=='' and endnode=='':
        result = graph.data('Match (' + startnode + ') return n  LIMIT ' + nodesOption[4]['name'])
    else:
        result= graph.data('Match p=('+startnode+')<-['+linknode+levkey+']->('+endnode+') return p  LIMIT '+nodesOption[4]['name'])
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj['_'+key]=node[key]
                # if node_obj.has_key('_src'):
                #     node_obj['symbol']='image://'+node_obj['_src']
                node_obj['name'] = node.identity
                node_obj['labels']=str(node.labels)[1:]
                node_obj['draggable'] ='true'
                node_obj['category'] ="n"+str(node_obj['name'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel['_'+relkey] = rel[relkey]
                noderel['name'] = rel.identity
                noderel['labels'] = path_name
                noderel['source'] = str(rel.start_node.identity)
                noderel['target'] = str(rel.end_node.identity)
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))


def graphCrudResult_dbquery():
    data = request.vars
    data.pop('name')
    data.pop('draggable')
    data.pop('category')
    node = 'n:' + data['labels']+'{'
    data.pop('labels')
    for key in data:
        if key[0]=='_':
            if type(data[key])==float:
                node = node + key[1:] + ':' + str(data[key]) + ','
            elif type(data[key]) == unicode:
                node = node + key[1:]+':"' + data[key]+'",'
            elif type(data[key]) == int:
                node = node + key[1:] + ':' + str(data[key]) + ','
            else:
                node = node + key[1:] + ':"' + str(data[key]) + '",'
    if len(data):
        node = node[:-1]
    node=node+'}'

    print node
    import datetime
    begin = datetime.datetime.now()
    result= graph.data('Match p=('+node+')-[*..1]-() return p  LIMIT 50')
    end = datetime.datetime.now()
    nodes=[]
    link=[]
    categorys=[]
    for row in result:
        for path in row:
            path_name=""
            for caa in path.types():
                path_name=caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj['_'+key]=node[key]
                # if node_obj.has_key('_src'):
                #     node_obj['symbol']='image://'+node_obj['_src']
                node_obj['name'] = node.identity
                node_obj['labels']=str(node.labels)[1:]
                node_obj['draggable'] ='true'
                node_obj['category'] ="n"+str(node_obj['name'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name':node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel['_'+relkey] = rel[relkey]
                noderel['name'] = rel.identity
                noderel['labels'] = path_name
                noderel['source'] = str(rel.start_node.identity)
                noderel['target'] = str(rel.end_node.identity)
                if noderel not in link:
                   link.append(noderel)
    return dict(data=nodes,link=link,categorys=categorys,time=str(end-begin))


def graphCrudResult_crud():
    datas = request.vars
    print datas
    data=datas.data
    data.pop('name')
    data.pop('draggable')
    data.pop('category')
    node = 'n:' + data['labels']+'{'
    data.pop('labels')
    for key in data:
        if key[0]=='_':
            if type(data[key])==float:
                node = node + key[1:] + ':' + str(data[key]) + ','
            elif type(data[key]) == unicode:
                node = node + key[1:]+':"' + data[key]+'",'
            elif type(data[key]) == int:
                node = node + key[1:] + ':' + str(data[key]) + ','
            else:
                node = node + key[1:] + ':"' + str(data[key]) + '",'
    if len(data):
        node = node[:-1]
    node=node+'}'

    import datetime
    print node
    result=None
    if datas.type==4:
        #delete
        print 'delete'
        begin = datetime.datetime.now()
        try:
            result = graph.data('MATCH (' + node + ') DELETE n')
        except:
            print 'err'
            result=graph.data('MATCH ('+node+')-[r]-() DELETE n,r')
        end = datetime.datetime.now()
        result = graph.data('MATCH (' + node + ') return count(1) as count')
        return dict(type=datas.type,count=result[0][0],time=str(end-begin))

    nodeadd = 'm:' + datas.add[0] + '{' + datas.add[1] + '}'
    r = 'r:' + datas.add[2] + '{' + datas.add[3] + '}'
    if datas.type==1 and datas.add[0] and datas.add[1]:
        print 'add'
        begin = datetime.datetime.now()
        result = graph.data('MERGE ('+nodeadd+') return m')
        end = datetime.datetime.now()
        nodes = []
        link = []
        categorys = []
        for row in result:
            for path in row:
                path_name = ""
                for caa in path.types():
                    path_name = caa
                for node in path.nodes:
                    node_obj = {}
                    for key in node.keys():
                        node_obj['_' + key] = node[key]
                    # if node_obj.has_key('_src'):
                    #     node_obj['symbol']='image://'+node_obj['_src']
                    node_obj['name'] = node.identity
                    node_obj['labels'] = str(node.labels)[1:]
                    node_obj['draggable'] = 'true'
                    node_obj['category'] = "n" + str(node_obj['name'])
                    if node_obj not in nodes:
                        nodes.append(node_obj)
                        categorys.append({'name': node_obj['category']})
                for rel in path.relationships:
                    noderel = {}
                    for relkey in rel.keys():
                        noderel['_' + relkey] = rel[relkey]
                    noderel['name'] = rel.identity
                    noderel['labels'] = path_name
                    noderel['source'] = str(rel.start_node.identity)
                    noderel['target'] = str(rel.end_node.identity)
                    if noderel not in link:
                        link.append(noderel)
        return dict(type=datas.type, data=nodes, link=link, categorys=categorys, time=str(end - begin))
    if datas.type==2 and datas.add[0] and datas.add[1] and datas.add[2] and datas.add[3] :
        print 'add 2'
        begin = datetime.datetime.now()
        result = graph.data('MATCH ('+node+') MERGE ('+nodeadd+') MERGE p=(m)-['+r+']->(n) return p')
        end = datetime.datetime.now()
        nodes = []
        link = []
        categorys = []
        for row in result:
            for path in row:
                path_name = ""
                for caa in path.types():
                    path_name = caa
                for node in path.nodes:
                    node_obj = {}
                    for key in node.keys():
                        node_obj['_' + key] = node[key]
                    # if node_obj.has_key('_src'):
                    #     node_obj['symbol']='image://'+node_obj['_src']
                    node_obj['name'] = node.identity
                    node_obj['labels'] = str(node.labels)[1:]
                    node_obj['draggable'] = 'true'
                    node_obj['category'] = "n" + str(node_obj['name'])
                    if node_obj not in nodes:
                        nodes.append(node_obj)
                        categorys.append({'name': node_obj['category']})
                for rel in path.relationships:
                    noderel = {}
                    for relkey in rel.keys():
                        noderel['_' + relkey] = rel[relkey]
                    noderel['name'] = rel.identity
                    noderel['labels'] = path_name
                    noderel['source'] = str(rel.start_node.identity)
                    noderel['target'] = str(rel.end_node.identity)
                    if noderel not in link:
                        link.append(noderel)
        return dict(type=datas.type, data=nodes, link=link, categorys=categorys, time=str(end - begin))
    if datas.type==3 and datas.add[0] and datas.add[1] and datas.add[2] and datas.add[3] :
        print 'add 3'
        begin = datetime.datetime.now()
        result = graph.data('MATCH ('+node+') MERGE ('+nodeadd+') MERGE p=(n)-['+r+']->(m) return p')
        end = datetime.datetime.now()
        nodes = []
        link = []
        categorys = []
        for row in result:
            for path in row:
                path_name = ""
                for caa in path.types():
                    path_name = caa
                for node in path.nodes:
                    node_obj = {}
                    for key in node.keys():
                        node_obj['_' + key] = node[key]
                    # if node_obj.has_key('_src'):
                    #     node_obj['symbol']='image://'+node_obj['_src']
                    node_obj['name'] = node.identity
                    node_obj['labels'] = str(node.labels)[1:]
                    node_obj['draggable'] = 'true'
                    node_obj['category'] = "n" + str(node_obj['name'])
                    if node_obj not in nodes:
                        nodes.append(node_obj)
                        categorys.append({'name': node_obj['category']})
                for rel in path.relationships:
                    noderel = {}
                    for relkey in rel.keys():
                        noderel['_' + relkey] = rel[relkey]
                    noderel['name'] = rel.identity
                    noderel['labels'] = path_name
                    noderel['source'] = str(rel.start_node.identity)
                    noderel['target'] = str(rel.end_node.identity)
                    if noderel not in link:
                        link.append(noderel)
        return dict(type=datas.type, data=nodes, link=link, categorys=categorys, time=str(end - begin))
    nodes = []
    link = []
    categorys = []
    for row in result:
        for path in row:
            path_name = ""
            for caa in path.types():
                path_name = caa
            for node in path.nodes:
                node_obj = {}
                for key in node.keys():
                    node_obj['_' + key] = node[key]
                # if node_obj.has_key('_src'):
                #     node_obj['symbol']='image://'+node_obj['_src']
                node_obj['name'] = node.identity
                node_obj['labels'] = str(node.labels)[1:]
                node_obj['draggable'] = 'true'
                node_obj['category'] = "n" + str(node_obj['name'])
                if node_obj not in nodes:
                    nodes.append(node_obj)
                    categorys.append({'name': node_obj['category']})
            for rel in path.relationships:
                noderel = {}
                for relkey in rel.keys():
                    noderel['_' + relkey] = rel[relkey]
                noderel['name'] = rel.identity
                noderel['labels'] = path_name
                noderel['source'] = str(rel.start_node.identity)
                noderel['target'] = str(rel.end_node.identity)
                if noderel not in link:
                    link.append(noderel)
    return dict(type=datas.type,data=nodes, link=link, categorys=categorys, time=str(end - begin))


def console():
    return dict()

def console1():
    return dict()